var API = (function () {
    const BASE_URL = 'https://study.duyiedu.com';
    const TOKEN_KEY = 'token';

    function get(path) {
        const headers = {};
        const token = localStorage.getItem(TOKEN_KEY);
        if (token) {
            headers.authorization = `Bearer ${token}`
        }
        return fetch(BASE_URL + path, {
            method: 'GET',
            headers
        })
    }

    function post(path, bodyObj) {
        const headers = {
            'Content-Type': 'application/json',
        };
        const token = localStorage.getItem(TOKEN_KEY);
        if (token) {
            headers.authorization = `Bearer ${token}`;
        }
        return fetch(BASE_URL + path, { headers, method: 'POST', body: JSON.stringify(bodyObj) });
    }


    // 注册
    async function register(userInfo) {
        // 拿到用户输入的账号、昵称和密码，然后提交服务器POST请求进行注册
        const result = await post('/api/user/reg', userInfo);
        return await result.json();
    }

    // 登录
    async function login(loginInfo) {
        const resp = await post('/api/user/login', loginInfo);
        const result = await resp.json();
        if (result.code === 0) { // 登录成功
            // 将响应头中的令牌保存到localStorage
            const token = resp.headers.get('authorization'); //拿到令牌
            localStorage.setItem(TOKEN_KEY, token);
        }
        return result;
    }

    // 验证账号
    async function exists(loginId) {
        const resp = await get('/api/user/exists?loginId=' + loginId);
        return resp.json();
    }

    // 当前登录的用户的信息
    async function profile() {
        const resp = await get('/api/user/profile');
        return resp.json();
    }

    // 发送聊天消息
    async function sendChat(content) {
        const resp = await post('/api/chat', { content });
        return resp.json();
    }

    // 获取连聊天记录
    async function getHistory() {
        const resp = await get('/api/chat/history');
        return resp.json();
    }

    // 退出登录
    function loginOut() {
        localStorage.removeItem(TOKEN_KEY);
    }

    return {
        register,
        login,
        exists,
        profile,
        sendChat,
        getHistory,
        loginOut
    };
})();